#include "bsp_sg90.h"

#include "los_task.h"

#include <stdio.h>
#include <stdint.h>

#define SG90_PWM_PORT               6       //GPIO0_PC3
#define SG90_PWM_FREQ               50      //固定频率

#define SG90_PWMDUTY_DOOROPEN       12
#define SG90_PWMDUTY_DOORCLOSE      3

typedef enum
{
    DOOR_STATE_IDLE,
    DOOR_STATE_SWITCHING
}door_state_t;

int sg90_init(void)
{
    int ret = 0;

    //pwm 初始化
    ret = IoTPwmInit(SG90_PWM_PORT);
    if(ret != 0)
    {
        printf("[%s] IoTPwmInit() failed:%d\n", __FUNCTION__, ret);
        return -1;
    }

    //设置开关 初始关门
    sg90_door_close();

    return 0;
}

int sg90_setPWM_duty(uint8_t duty)      // 3 ~ 12
{
    if(IoTPwmStart(SG90_PWM_PORT, duty, SG90_PWM_FREQ) != 0)
        return -1;

    return 0;
}

void sg90_test()
{
    int duty = 3;

    while(1)
    {
        if(duty > 12) duty = 3;
        sg90_setPWM_duty(duty);
        duty++;

        LOS_Msleep(1000);
    }
}

int sg90_door_open(void)
{
    if(IoTPwmStart(SG90_PWM_PORT, SG90_PWMDUTY_DOOROPEN, SG90_PWM_FREQ) != 0)
        return -1;

    // LOS_Msleep(200);
    // IoTPwmStop(SG90_PWM_PORT);

    return 0;
}

int sg90_door_close(void)
{
    if(IoTPwmStart(SG90_PWM_PORT, SG90_PWMDUTY_DOORCLOSE, SG90_PWM_FREQ) != 0)
        return -1;

    LOS_Msleep(100);
    IoTPwmStop(SG90_PWM_PORT);

    return 0;
}

